//
//  CycBleMessage.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/10.
//

#import "CycBleMessage.h"

@interface CycBleMessage()

@property (nonatomic, readwrite, assign) CYC_MessageBody body;
@property (nonatomic, readwrite, strong) NSData *extra;
@property (nonatomic, readwrite, strong) NSString *key;

@end

@implementation CycBleMessage

// 生成消息 --- 组包
- (instancetype)initWithTarget:(uint8_t)target cmd:(uint8_t)cmdID data:(NSData * __nullable)data {
    self = [super init];
    if (self) {
        CYC_MessageBody body;
        body.target = target;
        body.cmd = cmdID;
        body.len = data.length;
        body.data = data;
        self.body = body;
        
        Byte byte[5+sizeof(CYC_MessageBody)];
        byte[0] = CYC_PROTOCOL_HEADER;
        byte[1] = target;
        byte[2] = cmdID;
        byte[3] = data.length;
        
        int32_t sum = 0 ;
        for (int i = 0; i < data.length; i++) {
            Byte databyte[data.length];
            [data getBytes:databyte length:data.length];
            byte[4+i] = databyte[i];
            sum = sum + (int32_t)databyte[i];
        }
        
        int8_t checksum1 = sum%256;
        int8_t checksum2 = sum/256;
        byte[1+sizeof(CYC_MessageBody)] = checksum1;
        byte[2+sizeof(CYC_MessageBody)] = checksum2;
        byte[3+sizeof(CYC_MessageBody)] = CYC_PROTOCOL_FOOTER1;
        byte[4+sizeof(CYC_MessageBody)] = CYC_PROTOCOL_FOOTER2;

        NSData *extra = [NSData dataWithBytes:byte length:5+sizeof(CYC_MessageBody)];
        self.extra = extra;
        self.key = [NSString stringWithFormat:@"%0x_%0x", target,cmdID];

    }
    return self;
}

// 生成消息 --- 解包
- (instancetype)initWithData:(NSData * __nullable)data {
    self = [super init];
    if (self) {
        NSUInteger length = [data length];
        Byte *bytes = (Byte *) malloc(length);
        [data getBytes:bytes length:length];

        CYC_MessageBody body;
        body.target = bytes[1];
        body.cmd = bytes[2];
        body.len = bytes[3];
        body.data = [data subdataWithRange:NSMakeRange(4, data.length-8)];
        self.body = body;
        
        self.extra = data;
        self.key = [NSString stringWithFormat:@"%0x_%0x", body.target,body.cmd];

    }
    return self;
}

@end
